/**
 * @file sgp30.c
 * @brief 二氧化碳传感器
 *
 * @author 钟涛
 *
 * @date 2022-05-09
 *
 * @copyright 海南大学 - 追光者
 */

#include <rtthread.h>
#include <rtdevice.h>
#include "drv_common.h"
#include "app_main.h"

#include "sgp30.h"

#define DBG_TAG "sgp30"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>

sgp30_device_t sgp30_device;

/**
 * @brief 读取SGP30数据
 *
 * @attention 使用RT-Thread是soft_i2c，需要将延时时间调大
 *
 * @param CO2 二氧化碳保存指针
 * @param VOC VOC数值保存指针
 *
 * @return 是否读取成功
 */
bool sgp30_read(int16_t *CO2, int16_t *VOC)
{
    if (!sgp30_device) {
        *CO2 = -1;
        *VOC = -1;
        return false;
    }
    bool ret = sgp30_measure(sgp30_device);

    *CO2 = sgp30_device->eCO2;
    *VOC = sgp30_device->TVOC;
    return ret;
}

int test_sgp30(void)
{
    uint16_t CO2, VOC;
    int ret = sgp30_read(&CO2, &VOC);
    if (ret)
    {
        LOG_I("CO2: %u, VOC: %u", CO2, VOC);
    }
    else
    {
        LOG_E("test sgp30 fail.");
    }

    return ret;
}
MSH_CMD_EXPORT(test_sgp30, test sgp30);

int app_sgp30_init(void)
{
    sgp30_device = sgp30_create(SGP30_I2C_BUS_NAME);

    return 0;
}
INIT_DEVICE_EXPORT(app_sgp30_init);
